package com.portalEsporteClubeBahia.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.portalEsporteClubeBahia.app.ApplicationException;
import com.portalEsporteClubeBahia.app.bo.MatchBO;
import com.portalEsporteClubeBahia.app.vo.MatchVO;

public class FindAllMatchsAC extends HttpServlet {

	private static final long serialVersionUID = -3617276582176646023L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		JSONObject returning = new JSONObject();
		String status = "";
 		String message = "";
		JSONArray arrayData = new JSONArray();
		
		try {
			
			List<MatchVO> list = new MatchBO().findAll();
			
			if(list!=null){
				for(MatchVO match : list){
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("id", match.getId());
					jsonObject.put("championshipID", match.getChampionship().getId());
					jsonObject.put("championshipName", match.getChampionship().getName());
					jsonObject.put("stadiumID",match.getStadium().getId());
					jsonObject.put("stadimName", match.getStadium().getName());
					jsonObject.put("awayTeamId", match.getAwayTeam().getId());
					jsonObject.put("awayTeamName", match.getAwayTeam().getName());
					jsonObject.put("awayTeamShortName", match.getAwayTeam().getShortName());
					jsonObject.put("awayTeamUrlImage", match.getAwayTeam().getUrlImage());
					jsonObject.put("homeTeamID", match.getHomeTeam().getId());
					jsonObject.put("homeTeamName", match.getHomeTeam().getName());
					jsonObject.put("homeTeamShortName", match.getHomeTeam().getShortName());
					jsonObject.put("homeTeamUrlImage", match.getHomeTeam().getUrlImage());
					jsonObject.put("date", match.getDateFormat());
					jsonObject.put("dateUTC", match.getDateUTCFormat());
					jsonObject.put("homeGoal", match.getHomeGoals());
					jsonObject.put("awayGoal", match.getAwayGoals());
					jsonObject.put("finished", match.getFinished());
					jsonObject.put("active", match.getActive());
					arrayData.add(jsonObject);
				}
			}
			
			status =  "OK";
 			message = "";
			
		}catch (ApplicationException e) {
			status  =  "ERROR";
  			message = e.getMessage();
		}
		
		returning.put("status",status);
 		returning.put("message",message);
 		returning.put("data",arrayData);
		
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(returning.toString());
	}

}
